package com.itlong.cloud.rabbitmq.config;

import com.itlong.cloud.utils.rabbitMQ.MessageSendUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by itlong on 2017/8/7.
 */
@Component
public class MessageSender implements RabbitTemplate.ConfirmCallback {


    private static final Logger LOG = LoggerFactory.getLogger(MessageSender.class);

    private RabbitTemplate rabbitTemplate;

/*    @Autowired
    private AmqpTemplate rabbitTemplate;*/

    @Autowired
    public MessageSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String message) {
        if (ack) {
            //LOG.info("【用户服务消息发送成功】-" + correlationData);
        } else {
            //为保证消息发送端的安全性，后续增加对失败消息入库的操作。
            LOG.info("【支付服务消息发送失败】-" + "消息唯一码:" + correlationData + "消息体：" + message);
        }
    }



    //发送消息，不需要实现任何接口，供外部调用。
    public void send(String queueName,String msg,String exchange,String routingKey) throws Exception {
        MessageSendUtil.send(queueName,msg,exchange,routingKey,rabbitTemplate);
    }

}
